import axios from 'axios'
import { useLoginStore } from '@/stores/index'
// Add a request interceptor
axios.interceptors.request.use(
  function (config) {
    const loginStore = useLoginStore()
    const token = loginStore.token
    config.headers.Authorization = `Bearer ${token}`
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  },
)

// Add a response interceptor
axios.interceptors.response.use(
  function (response) {
    const loginStore = useLoginStore()
    const { authorization } = response.headers
    if (authorization) {
      loginStore.setToken(authorization)
    }
    return response
  },
  function (error) {
    const { status } = error.response
    if (status === 401) {
      const loginStore = useLoginStore()
      loginStore.setToken('')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  },
)
